package org.thunms.framework.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.ClassUtils;
import org.springframework.util.DefaultPropertiesPersister;
import org.springframework.util.PropertiesPersister;

public class UtilSystemProperties extends PropertyPlaceholderConfigurer {
	private static final String PROPERTIES_PATTERN = "/*.properties";
	private static final String XML_FILE_EXTENSION=".xml";
	private static Date limitDate=null;
	private static String thunms_webapp_root;
	private static Properties props;
	private static final Logger logger = LoggerFactory.getLogger(UtilSystemProperties.class);
	private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
	private PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();
	private boolean ignoreResourceNotFound = false;
	private String fileEncoding;
	private  List<String> packagesToScan;
	static{
		limitDate=UtilDate.getDateStart(new Date(), 1);
	}
	public void setPackagesToScan(List<String> packagesToScan) {
		this.packagesToScan = packagesToScan;
	}
	@Override
	public void setFileEncoding(String encoding) {
		super.setFileEncoding(encoding);
		this.fileEncoding=encoding;
	}


	@Override
	protected void loadProperties(Properties props) throws IOException {
		//加载自定义文件
		if(this.packagesToScan!=null&&!this.packagesToScan.isEmpty()){
			for (String pkg : this.packagesToScan) {
				String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
						ClassUtils.convertClassNameToResourcePath(pkg) + PROPERTIES_PATTERN;
				Resource[] resources = this.resourcePatternResolver.getResources(pattern);
				if(resources!=null){
					for (Resource location : resources) {
						if (logger.isInfoEnabled()) {
							logger.info("加载  properties file from " + location);
						}
						InputStream is = null;
						try {
							is = location.getInputStream();
							String filename = location.getFilename();
							if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
								this.propertiesPersister.loadFromXml(props, is);
							}
							else {
								if (this.fileEncoding != null) {
									this.propertiesPersister.load(props, new InputStreamReader(is, this.fileEncoding));
								}
								else {
									this.propertiesPersister.load(props, is);
								}
							}
						}
						catch (IOException ex) {
							if (this.ignoreResourceNotFound) {
								if (logger.isWarnEnabled()) {
									logger.warn("无法加载 load properties from " + location + ": " + ex.getMessage());
								}
							}
							else {
								throw ex;
							}
						}
						finally {
							if (is != null) {
								is.close();
							}
						}
					}	
				}
				
			}
			
		}
		
		
		
		super.loadProperties(props);
		this.props=props;
	}


	
	/** Compares the specified property to the compareString, returns true if they are the same, false otherwise
     * @param resource The name of the resource - if the properties file is 'webevent.properties', the resource name is 'webevent'
     * @param name The name of the property in the properties file
     * @param compareString The String to compare the property value to
     * @return True if the strings are the same, false otherwise
     */
    public static boolean propertyValueEquals( String name, String compareString) {
        String value = getPropertyValue(name);

        if (value == null) return false;
        return value.trim().equals(compareString);
    }

    /** Compares Ignoring Case the specified property to the compareString, returns true if they are the same, false otherwise
     * @param resource The name of the resource - if the properties file is 'webevent.properties', the resource name is 'webevent'
     * @param name The name of the property in the properties file
     * @param compareString The String to compare the property value to
     * @return True if the strings are the same, false otherwise
     */
    public static boolean propertyValueEqualsIgnoreCase( String name, String compareString) {
        String value = getPropertyValue( name);

        if (value == null) return false;
        return value.trim().equalsIgnoreCase(compareString);
    }

    /** Returns the value of the specified property name from the specified resource/properties file.
     * If the specified property name or properties file is not found, the defaultValue is returned.
     * @param resource The name of the resource - if the properties file is 'webevent.properties', the resource name is 'webevent'
     * @param name The name of the property in the properties file
     * @param defaultValue The value to return if the property is not found
     * @return The value of the property in the properties file, or if not found then the defaultValue
     */
    public static String getPropertyValue( String name, String defaultValue) {
        String value = getPropertyValue( name);

        if (value==null||"".equals(value))
            return defaultValue;
        else
            return value;
    }

    public static double getPropertyNumber( String name, double defaultValue) {
        String str = getPropertyValue( name);
        if (str == null) {
            return defaultValue;
        }

        try {
            return Double.parseDouble(str);
        } catch (NumberFormatException nfe) {
            return defaultValue;
        }
    }

    public static double getPropertyNumber( String name) {
        return getPropertyNumber( name, 0.00000);
    }
    
    public static Boolean getPropertyBoolean(String name){
		return Boolean.parseBoolean(getPropertyValue(name));
    }
 
    /** Returns the value of the specified property name from the specified resource/properties file
     * @param resource The name of the resource - can be a file, class, or URL
     * @param name The name of the property in the properties file
     * @return The value of the property in the properties file
     */
    public static String getPropertyValue( String name) {
        if (name == null || name.length() <= 0) return "";
        String value = props.getProperty(name);
        return value == null ? "" : value.trim();
    }
    /**
     * 增加或改变属性的值.
     * @param name
     * @param value
     */

    public static void setPropertyValue(String name,String value){
    	props.setProperty(name, value);
    } 
    public static void romveProperty(String name){
    	props.remove(name);
    }
    
    public static void setThunmsWebappRoot(String value){
    	thunms_webapp_root=value;
    }
    public static String getThunmsWebappRoot(){
    	return thunms_webapp_root;
    }
    /**
     * 获取平台附件存放的根路径
     * @return
     */
    public static String getAccessoryDirectoryRootPath(){
		return UtilSystemProperties.getPropertyValue("thunms.accessory.root.path", UtilSystemProperties.getThunmsWebappRoot());
    	
    }
	public static Date getLimitDate() {
		return limitDate;
	}
	
}
